import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { View, Image, Swiper, SwiperItem, Text, RichText, ScrollView } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'
import { AtIcon, AtFloatLayout, AtList, AtListItem, AtInputNumber, AtAvatar, AtRate } from 'taro-ui'
import Stores from '../../stores/storeIdentifier'
import ProductStore from '../../stores/productStore'
import CartSore from '../../stores/cartStore'
import './index.scss'
import { ProductDto } from '../../services/product/dto/productDto';
import { ProductCommentListDto } from '../../services/product/dto/productCommentListDto';
import { PagedList } from '../../services/dto/pagedList';
import { SpecificationValueDto } from '../../services/product/dto/specificationValueDto';
import { ShoppingCartInputDto } from '../../services/cart/dto/shoppingCartInputDto';
import ModuleTypeIds from '../../services/dto/moduleTypeIds';
import { SkuDto } from '../../services/product/dto/skuDto';
import { ProductCommentStatisticsDto } from '../../services/product/dto/productCommentStatisticsDto'

export interface IIndexProps {
  productStore: ProductStore,
  cartStore: CartSore
}

@inject(Stores.ProductStore, Stores.CartStore)
@observer
class Index extends Component<IIndexProps> {
  product: ProductDto = new ProductDto()
  noSkuList: number[] = []
  tempList: number[] = []
  initialNoSkuList: number[] = []
  selectSpecList: number[] = []
  selectItemList: SpecificationValueDto[] = []

  comments: PagedList<ProductCommentListDto>
  model: ShoppingCartInputDto = new ShoppingCartInputDto()
  currentSku: SkuDto
  followed = false
  statistics: ProductCommentStatisticsDto
  state = {
    opened: false,
    tempSeletText: '',
    cartText: ''
  }
  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '产品详情',
    backgroundColor: '#f4f4f4'
  }

  constructor(props: any) {
    super(props)
    this.model.giftType = this.$router.params.type
    console.log(this.$router.params.type)
    this.setState({})
  }

  async componentDidMount() {

    await this.getProduct(this.$router.params.id)
  }

  async componentDidShow() {
    let pages = getCurrentPages()
    if (pages) {
      let prev = pages[pages.length - 1]
      if (prev.data.isAuthorize) {
        prev.setData({
          isAuthorize: false
        })
      }
    }
  }

  getProduct = async (id) => {
    await this.props.productStore.getProduct(id)
    const { product } = this.props.productStore
    this.product = product

    this.product.specifications.map((item) => {
      item.specificationValues.map((spec) => {
        let currentSku = this.product.skus.filter(m => m.id.includes(spec.id + ""))
        let length = currentSku.filter(m => m.stock == 0).length
        if (currentSku.length == length) {
          this.noSkuList.push(spec.id)
        }
      })
    })
    this.model.productId = id
    this.model.moduleTypeId = ModuleTypeIds.Product

    this.model.quantity = 1
    this.initialNoSkuList = this.noSkuList
    if (this.product.skus.length == 1 && this.product.skus[0].stock > 0) {
      this.model.skuId = this.product.skus[0].id
      this.selectItemList = []
      //组装选择的规格名称
      this.product.specifications.map((item) => {
        let spec = item.specificationValues.find(m => m.specificationId == item.id)
        if (spec) {
          this.selectItemList.push(spec)
          this.selectSpecList.push(spec.id)
          if (this.state.tempSeletText.includes('已选择')) {
            this.state.tempSeletText += ' ' + spec.name
          } else {
            this.state.tempSeletText = '已选择： ' + spec.name
          }
        }
      })

      this.setState({
        selectText: this.state.tempSeletText + ' x' + this.model.quantity,
        cartText: this.state.tempSeletText
      })
    }
    this.setState({
      product: product
    })
  }

  openCart = () => {
    this.setState({ opened: true })
  }

  select = () => {
    this.setState({ opened: false })
  }

  handleChange = (value) => {
    if (value > 99) {
      value = 99
      Taro.showToast({ title: '已达到最大数量', icon: 'none' })
    }
    this.model.quantity = value
    if (this.currentSku) {
      if (value > this.currentSku.stock) {
        Taro.showToast({ title: '已达到最大库存数量', icon: 'none' })
        this.model.quantity = this.currentSku.stock
      }
    }
    this.setState({})
  }

  handleBlur() {

  }

  //加入购物车
  join = async () => {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
      return
    }

    if (!this.state.opened && !this.model.skuId) {
      this.openCart()
      return
    }

    if (!this.model.skuId) {
      Taro.showToast({
        title: '请选择商品规格',
        icon: 'none',
      })
      return
    }

    if (this.product.stock === 0) {
      Taro.showToast({
        title: '商品已售罄',
        icon: 'none',
      })
      return
    }
    if (!this.product.isPublish) {
      Taro.showToast({
        title: '已下架',
        icon: 'none',
      })
      return
    }
    console.log(this.model.giftType)
    await this.props.cartStore.createShoppingCartAsync(this.model)
    this.setState({})
    Taro.navigateTo({
      url: '/pages/index/index?type=' + this.$router.params.type
    })
  }

  selectSpec(event) {
    let spec = event.currentTarget.dataset.item
    //存在的话，移除掉
    if (this.selectSpecList.includes(spec.id)) {
      this.selectSpecList = this.selectSpecList.filter(m => m != spec.id)
      this.model.skuId = ''
      this.setState({
        selectText: '请选择规格或颜色',
        tempSeletText: '',
        cartText: '已选择：'
      })
    } else {
      //维护选中的规格，首先清空同级别
      let specLevel = this.product.specifications.filter(m => m.id == spec.specificationId)[0]
      this.tempList = []
      specLevel.specificationValues.map((specItem) => {
        this.tempList.push(specItem.id)
      })
      this.selectSpecList = this.selectSpecList.filter(m => !this.tempList.includes(m))
      this.selectSpecList.push(spec.id)

    }
    this.setSpecifcation()
    this.setState({})
  }

  setSpecifcation() {
    //初始化最初的状态
    this.noSkuList = []
    this.selectItemList = []
    this.state.tempSeletText = ''

    this.initialNoSkuList.map((item) => {
      this.noSkuList.push(item)
    })
    if (this.selectSpecList.length) {
      //重置当前选项下的所有的sku状态
      //遍历所有选中项
      this.selectSpecList.map((single) => {
        //根据当前选中项，获取所有概率sku
        let skuList = this.product.skus.filter(m => m.id.includes('_' + single.toString()))
        this.product.specifications.map((item) => {
          let exist = item.specificationValues.find(m => m.id == single)
          if (!exist) {
            //查找当前规格对应的其他规格是不是存在库存为0的情况
            item.specificationValues.map((current) => {
              let currentSku = skuList.filter(m => m.id.includes(current.id.toString()))
              let length = currentSku.filter(m => m.stock == 0).length
              if (currentSku.length == length) {
                this.noSkuList.push(current.id)
              }
            })
          } else {
            this.selectItemList.push(exist)
          }
        })
      })


      //组装选择的规格名称
      this.product.specifications.map((item) => {
        let spec = this.selectItemList.find(m => m.specificationId == item.id)
        if (spec) {
          if (this.state.tempSeletText.includes('已选择')) {
            this.state.tempSeletText += ' ' + spec.name
          } else {
            this.state.tempSeletText = '已选择： ' + spec.name
          }
        }
      })

      if (this.product.specifications.length == this.selectSpecList.length) {
        this.state.cartText = this.state.tempSeletText
        let specStr = this.model.productId
        let ids = this.selectSpecList.sort((a, b) => {
          return a - b
        })
        specStr += '_' + ids.join('_')
        let sku = this.product.skus.find(m => m.id.includes(specStr))

        if (sku) {
          this.product.price = sku.price
          this.model.skuId = sku.id
          this.currentSku = sku
          if (this.model.quantity > sku.stock) {
            Taro.showToast({ title: '已达到最大数量', icon: 'none' })
            this.model.quantity = sku.stock
          }
        }
      }
    }
    this.setState({})
  }

  onShareAppMessage() {
    let tmpPath = '/pages/product/index?id=' + this.$router.params.id
    return {
      title: this.product.name,
      path: tmpPath,
      success: function (res) {
        console.log('success')
      },
      fail: function (res) {
        console.log('fail')
      },
      complete: function () {
        console.log('complete')
      }
    }
  }

  render() {

    return (
      <View className='product-page'>
        <Swiper
          className='swiper-container swiper-product'
          circular
          indicatorDots
          indicatorColor='#999'
          indicatorActiveColor='#f6293a'
          autoplay
        >
          {this.product && this.product.images && this.product.images.filter(n => !n.isFirstShow).map((item, index) => (
            <SwiperItem key={index}>
              <Image mode='aspectFill' src={item.url} />
            </SwiperItem>
          ))}
        </Swiper>
        <View className='mall-detail-block ratina-bd bd-b'>
          <View className='price'>
            <Text className='strong'>￥{this.product.price}</Text>
          </View>
          <View className='h1'>{this.product.name}</View>
        </View>
        <View className='disc'>但愿你和Ta的笑容里有着相同的内容...</View>
        <View className='fixed-btns'>
          <View className='fixed-btn' onClick={this.join}> </View>
        </View>
        <AtFloatLayout className='cart-model-wrap' isOpened={this.state.opened} title='购物车' onClose={this.select}>
          <View className='cart-model'>
            <View className='pro-media'>
              <Image className='pro-media-hd' mode='aspectFill' src={!this.currentSku.featuredImageUrl ? this.product.featuredImageUrl : this.currentSku.featuredImageUrl} />
              <View className='pro-media-bd'>
                <View className='price'>价格：￥{this.product.price}</View>
                <View className='checked'>{this.state.cartText}</View>
              </View>
            </View>
            <ScrollView
              className='scrollview'
              scrollY
              scrollWithAnimation
              style='height: 260px;'
            >
              {
                this.product.specifications && this.product.specifications.map((item) => (
                  <View className='cart-panel'>
                    <View className='cart-panel-header'>{item.name}</View>
                    <View className='cart-panel-body'>
                      <View className='tag-list'>
                        {
                          item.specificationValues && item.specificationValues.map((spec) => (
                            <View>
                              {this.noSkuList.includes(spec.id) && (
                                <View className='tag-cell disabled'>{spec.name}</View>
                              )}
                              {!this.noSkuList.includes(spec.id) && !this.selectSpecList.includes(spec.id) && (
                                <View className='tag-cell' data-item={spec} onClick={this.selectSpec}>{spec.name}</View>
                              )}
                              {!this.noSkuList.includes(spec.id) && this.selectSpecList.includes(spec.id) && (
                                <View className='tag-cell tag-active' data-item={spec}
                                  onClick={this.selectSpec}>{spec.name}</View>
                              )}
                            </View>
                          ))
                        }
                      </View>
                    </View>
                  </View>
                ))
              }

              <View className='cart-panel'>
                <View className='cart-panel-header'>数量</View>
                <View className='cart-panel-body'>
                  <AtInputNumber
                    className='sc-input-number'
                    min={0}
                    max={99}
                    step={1}
                    value={this.model.quantity}
                    onChange={this.handleChange.bind(this)}
                    onBlur={this.handleBlur}
                    type='number'
                  />
                </View>
              </View>
            </ScrollView>
          </View>
        </AtFloatLayout>

      </View>
    )
  }
}

export default Index
